package com.rhino.security.service.impl;

import com.rhino.security.service.MyPasswordEncoder;
import com.rhino.security.vo.JwtUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.List;


/**
 * 用户认证自定义流程
 */
@Slf4j
public class JwtUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private MyPasswordEncoder passwordEncoder;

    /**
     * 通过登录用户获取认证通过的用户，未找到用户需抛出异常；密码错误时返回NULL或抛出异常
     * @param userLoginName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userLoginName) throws UsernameNotFoundException {
        log.debug("登录的用户名为：{}", userLoginName);
        //正常业务这里应该获取数据库用户信息，用户、密码、权限及角色等，这里模拟数据使用。正常业务会从数据库查询加密的密码和password比对
        //给当前用户2个权限，正常业务从数据库查询；权限一般就是对菜单或某个按钮访问的标准；
        String authorities="Admin,Broker";
        //给当前用户添加一些角色，名称如果以"ROLE_" 开头，表示当前是角色；@PreAuthorize("hasRole('Role')")
        authorities+=",ROLE_Employee,ROLE_Manager,ROLE_Admin";
        String password=passwordEncoder.privateEncode("123");

        //这里模拟没有当前用户
        if(!userLoginName.startsWith("jake_")){
            throw new UsernameNotFoundException(userLoginName+",未找到当前用户信息");
        }

        //模拟获取当前登录用户
        List<GrantedAuthority> GrantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
        JwtUser jwtUser = new JwtUser(userLoginName, password, userLoginName,GrantedAuthorities);
        return jwtUser;

    }
}
